package com.atguigu.tingshu.order.strategy.impl;

import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.order.OrderDerate;
import com.atguigu.tingshu.model.order.OrderDetail;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.order.mapper.OrderDerateMapper;
import com.atguigu.tingshu.order.mapper.OrderDetailMapper;
import com.atguigu.tingshu.order.mapper.OrderInfoMapper;
import com.atguigu.tingshu.order.strategy.SaveOrderStrategy;
import com.atguigu.tingshu.vo.order.OrderDerateVo;
import com.atguigu.tingshu.vo.order.OrderDetailVo;
import com.atguigu.tingshu.vo.order.OrderInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBlockingDeque;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class WeiXinSaveOrderStrategy implements SaveOrderStrategy {


    @Autowired
    private  OrderInfoMapper orderInfoMapper;


    @Autowired
    private OrderDetailMapper orderDetailMapper ;

    @Autowired
    private OrderDerateMapper orderDerateMapper ;

    @Autowired
    private RedissonClient redissonClient;

    /*
    *   这个是微信支付保存订单数据
    *   存在的问题:
    *       用户生成了订单数据,发送给了后端,生成了订单信息,但是一直没有付款,会导致数据一直保存在数据库里面,影响存储
    *
    *   解决方案:规定一个时间,让用户去支付,没有支付,改变支付的状态,取消订单
    *
    *
    *   方法:
    *       更改订单的状态,把订单的状态变为取消,后期通过定时任务,查询已经取消的订单,放入历史订单表中
    *
    *   实现方案:
    *          延迟队列(存储延迟的任务)
    * */
    @Transactional
    @Override
    public OrderInfoVo saveOrderInfo(OrderInfoVo orderInfoVo) {
        log.info("提交订单任务开始了");
        this.saveOrderInfoAndDetailAndDerateInfo(orderInfoVo , orderInfoMapper , orderDetailMapper , orderDerateMapper);
        return orderInfoVo;
    }

    @Override
    public String getPayWay() {
        return SystemConstant.ORDER_PAY_WAY_WEIXIN;
    }

    @Override
    public void saveOrderAfterProcess(OrderInfoVo orderInfoVo) {
        //发布延迟任务 这是后续操作
        this.sendDelayTask(orderInfoVo);
    }

    //向redis中发送延迟任务
    public void sendDelayTask(OrderInfoVo orderInfoVo) {

        //向redis中发布延迟任务 使用的是redission中的延迟任务
        RBlockingDeque<Object> blockingDeque = redissonClient.getBlockingDeque("order:info:delay:queue");  //获取堵塞队列
        RDelayedQueue<Object> delayedQueue = redissonClient.getDelayedQueue(blockingDeque);
        delayedQueue.offer(orderInfoVo.getTradeNo(), RedisConstant.ORDER_INFO_TIME_OUT , TimeUnit.SECONDS);
    }





}
